package org.vison.wonfu.framework.config;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureOrder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.Ordered;
import org.springframework.core.env.Environment;
import org.vison.wonfu.framework.commons.Constants;
import org.vison.wonfu.framework.config.utils.MultiLevelConfigProvider;

@Configuration
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
public class ConfigAutoConfigure {

    private final static Logger logger = org.slf4j.LoggerFactory.getLogger(ConfigAutoConfigure.class);

    private static final String NAMESPACE = "application"; // Apollo命名空间


    private final Environment environment;

    @Autowired
    public ConfigAutoConfigure(Environment environment) {
        this.environment = environment;
        listenApolloChange(environment);
    }

    private void listenApolloChange(Environment environment) {
        String[] namespaces = environment.getProperty(Constants.APOLLO_LISTEN_NAMESPACES, String.class, NAMESPACE)
                .split(",");
        for (String namespace : namespaces) {
            Config config = ConfigService.getConfig(namespace);
            config.addChangeListener(changeEvent ->
                    changeEvent.changedKeys().forEach(key -> {
                        logger.info("Apollo配置变更: namespace {}, key {},{} => {}", namespace,
                                key, changeEvent.getChange(key).getOldValue(),
                                changeEvent.getChange(key).getNewValue());
                    }));
        }
    }

    // 项目启动时初始化日志级别


    @Primary
    @Bean
    public MultiLevelConfigProvider defaultConfigUtils() {
        return new MultiLevelConfigProvider(environment, NAMESPACE);
    }

    @Bean(name = Constants.GOVERNANCE_BEAN)
    public MultiLevelConfigProvider goveranceConfigUtils() {
        return new MultiLevelConfigProvider(environment, Constants.GOVERNANCE_NAMESPACE);
    }

}